<?php

/**
 * 行为绑定
 */
\think\Hook::add('app_init', 'app\\common\\behavior\\InitConfigBehavior');
header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
setlocale(LC_ALL, 'zh_CN.utf8');  //设定地域
// header('Access-Control-Allow-Methods:POST');
/**
 * 返回对象
 * @param $array 响应数据
 */
function resultArray($array)
{
    if (isset($array['data'])) {
        $array['error'] = '';
        $code = 200;
    } elseif (isset($array['error']) && !isset($array['code'])) {
        $code = 400;
        $array['data'] = '';
    } elseif (isset($array['code'])) {
        $code = $array['code'];
        $array['data'] = '';
    }
    return json([
        'code' => $code,
        'data' => $array['data'],
        'error' => $array['error'],
    ]);
}

/**
 * 方法之间调用统一返回结果 - jago
 */
function operationRes($isSuccess, $info='未填写', $data=[], $other=[]) {
    return (object)[
        'isSuccess' => $isSuccess,
        'info' => $info,
        'data' => (object)$data,
        'other' => (object)$other
    ];
}

/**
 * 接口返回结果 | 基于resultArray()和operationRes()使用 - jago
 */
function JRes($res) {
    if ($res->isSuccess) {
        return resultArray(['data' => $res->info]);
    }else {
        return resultArray(['error' => $res->info]);
    }
}

function returnJson($array)
{

    if (isset($array['data'])) {
        $array['error'] = '';
        $code = 200;
    } elseif (isset($array['error'])) {
        if ($array['code']) {
            $code = $array['code'];
        } else {
            $code = 600;
        }
        $array['data'] = [];
    }
    return json([
        'code' => $code,
        'data' => $array['data'],
        'error' => $array['error'],
    ]);
}
/**
 * 用户密码加密方法
 * @param  string $str      加密的字符串
 * @param  [type] $auth_key 加密符
 * @return string           加密后长度为32的字符串
 */
function user_md5($str, $auth_key = '')
{
    return '' === $str ? '' : md5(sha1($str) . $auth_key);
}

function csrf_field()
{
    echo '<input type="hidden" name="_token" value="' . config('csrf_token') . '">';
}

function icons()
{
    $icons['type'] = ' glyphicon';
    $icon_json = '["asterisk","plus","euro","minus","cloud","envelope","pencil","glass","music","search","heart","star","star-empty","user","film","th-large","th","th-list","ok","remove","zoom-in","zoom-out","off","signal","cog","trash","home","file","time","road","download-alt","download","upload","inbox","play-circle","repeat","refresh","list-alt","lock","flag","headphones","volume-off","volume-down","volume-up","qrcode","barcode","tag","tags","book","bookmark","print","camera","font","bold","italic","text-height","text-width","align-left","align-center","align-right","align-justify","list","indent-left","indent-right","facetime-video","picture","map-marker","adjust","tint","edit","share","check","move","step-backward","fast-backward","backward","play","pause","stop","forward","fast-forward","step-forward","eject","chevron-left","chevron-right","plus-sign","minus-sign","remove-sign","ok-sign","question-sign","info-sign","screenshot","remove-circle","ok-circle","ban-circle","arrow-left","arrow-right","arrow-up","arrow-down","share-alt","resize-full","resize-small","exclamation-sign","gift","leaf","fire","eye-open","eye-close","warning-sign","plane","calendar","random","comment","magnet","chevron-up","chevron-down","retweet","shopping-cart","folder-close","folder-open","resize-vertical","resize-horizontal","hdd","bullhorn","bell","certificate","thumbs-up","thumbs-down","hand-right","hand-left","hand-up","hand-down","circle-arrow-right","circle-arrow-left","circle-arrow-up","circle-arrow-down","globe","wrench","tasks","filter","briefcase","fullscreen","dashboard","paperclip","heart-empty","link","phone","pushpin","usd","gbp","sort","sort-by-alphabet","sort-by-alphabet-alt","sort-by-order","sort-by-order-alt","sort-by-attributes","sort-by-attributes-alt","unchecked","expand","collapse-down","collapse-up","log-in","flash","log-out","new-window","record","save","open","saved","import","export","send","floppy-disk","floppy-saved","floppy-remove","floppy-save","floppy-open","credit-card","transfer","cutlery","header","compressed","earphone","phone-alt","tower","stats","sd-video","hd-video","subtitles","sound-stereo","sound-dolby","sound-5-1","sound-6-1","sound-7-1","copyright-mark","registration-mark","cloud-download","cloud-upload","tree-conifer","tree-deciduous"]';
    $icons['arr'] = json_decode($icon_json, 1);
    return $icons;
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}

function rjson($data = array(), $code = 200, $error = '')
{
    //return json($data,)
}

function script_path($name, $type)
{

    $path = str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']);

    $assets_json = file_get_contents('../public/assets.json');
    $assets = json_decode($assets_json, 1);
    echo $path . $assets[$name][$type];
}
// 应用公共文件
function password_md5($str, $auth_key = '')
{
    return '' === $str ? '' : md5(sha1($str) . $auth_key);
}

function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = null;
    if ($ip !== null) {
        return $ip[$type];
    }

    if ($_SERVER['HTTP_X_REAL_IP']) {
        //nginx 代理模式下，获取客户端真实IP
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        //客户端的ip
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //浏览当前页面的用户计算机的网关
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) {
            unset($arr[$pos]);
        }

        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR']; //浏览当前页面的用户计算机的ip地址
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function download_result_f($zip_file, $files)
{

    if (file_exists($zip_file)) {
        unlink($zip_file);
    }
    //重新生成文件
    $zip = new ZipArchive(); //使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
    if ($zip->open($zip_file, ZIPARCHIVE::CREATE) !== true) {
        exit('无法打开文件，或者文件创建失败');
    }
    foreach ($files['mp3'] as $k => $val) {
        if (file_exists($val)) {
            $fp = path_info($val);
            $zip->addFile($val, $files['names'][$k] . '.mp3'); //第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
    }
    foreach ($files['txt'] as $k => $val) {
        if (file_exists($val)) {
            $fp = path_info($val);
            $zip->addFile($val, $files['names'][$k] . '.txt'); //第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
    }
    foreach ($files['readme'] as $k => $val) {
        if (file_exists($val)) {
            $fp = path_info($val);
            $zip->addFile($val, $fp['basename']); //第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
    }
    $zip->close(); //关闭
    if (!file_exists($zip_file)) {
        exit("无法找到文件"); //即使创建，仍有可能失败。。。。
    }
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-disposition: attachment; filename=' . basename($zip_file)); //文件名
    header("Content-Type: application/zip"); //zip格式的
    header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
    header('Content-Length: ' . filesize($zip_file)); //告诉浏览器，文件大小
    @readfile($zip_file);
    exit;
}

function download_result_e($zip_file, $files)
{

    if (file_exists($zip_file)) {
        unlink($zip_file);
    }
    //重新生成文件
    $zip = new ZipArchive(); //使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
    if ($zip->open($zip_file, ZIPARCHIVE::CREATE) !== true) {
        exit('无法打开文件，或者文件创建失败');
    }
    foreach ($files['mp3'] as $k => $val) {
        if (file_exists($val)) {
            //$fp = path_info($val);
            $zip->addFile($val, $files['names'] . '.mp3'); //第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
    }
    foreach ($files['docx'] as $k => $val) {
        if (file_exists($val)) {
            //$fp = path_info($val);
            $zip->addFile($val, $files['names'] . '.docx'); //第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
    }
    // foreach ($files['readme'] as $k => $val) {
    //     if (file_exists($val)) {
    //         $fp = path_info($val);
    //         $zip->addFile($val, $fp['basename']); //第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
    //     }
    // }
    $zip->close(); //关闭
    if (!file_exists($zip_file)) {
        exit("无法找到文件"); //即使创建，仍有可能失败。。。。
    }
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-disposition: attachment; filename=' . basename($zip_file)); //文件名
    header("Content-Type: application/zip"); //zip格式的
    header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
    header('Content-Length: ' . filesize($zip_file)); //告诉浏览器，文件大小
    @readfile($zip_file);
    exit;
}


function path_info($filepath)
{
    $path_parts = array();
    $path_parts['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath, '/')), "/") . "/";
    $path_parts['basename'] = ltrim(substr($filepath, strrpos($filepath, '/')), "/");
    $path_parts['extension'] = substr(strrchr($filepath, '.'), 1);
    $path_parts['filename'] = ltrim(substr($path_parts['basename'], 0, strrpos($path_parts['basename'], '.')), "/");
    return $path_parts;
}
/** 
 * 改造版下载文件，添加一个属性
 * @file 文件路径
 * @changeName 将下载文件改名，如果不传默认为空，参照之前的格式输出名字，不带后缀
 */
function download_result_one($file, $changeName = "")
{
    $filePath = $file;
    if (!empty($filePath)) {
        $fileInfo = pathinfo($filePath);
        $fileName = $fileInfo['basename'];
        $fileExtnesion = $fileInfo['extension'];
        $default_contentType = "application/octet-stream";
        $content_types_list = mimeTypes();
        if (array_key_exists($fileExtnesion, $content_types_list)) {
            $contentType = $content_types_list[$fileExtnesion];
        } else {
            $contentType = $default_contentType;
        }
        if (file_exists($filePath)) {
            $size = filesize($filePath);
            $offset = 0;
            $length = $size;
            if (isset($_SERVER['HTTP_RANGE'])) {
                preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
                $offset = intval($matches[1]);
                $length = intval($matches[2]) - $offset;
                $fhandle = fopen($filePath, 'r');
                fseek($fhandle, $offset);
                $data = fread($fhandle, $length);
                fclose($fhandle);
                header('HTTP/1.1 206 Partial Content');
                header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $size);
            }
            $fileName = $changeName ? $changeName . substr($fileName, strrpos($fileName, '.')) : $fileName;
            header("Content-Disposition: attachment;filename=" . $fileName);
            header('Content-Type: ' . $contentType);
            header("Accept-Ranges: bytes");
            header("Pragma: public");
            header("Expires: -1");
            header("Cache-Control: no-cache");
            header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
            header("Content-Length: " . filesize($filePath));
            $chunksize = 8 * (1024 * 1024); //8MB (highest possible fread length) 
            if ($size > $chunksize) {
                $handle = fopen($filePath, 'rb');
                $buffer = '';
                while (!feof($handle) && (connection_status() === CONNECTION_NORMAL)) {
                    $buffer = fread($handle, $chunksize);
                    print $buffer;
                    ob_flush();
                    flush();
                }
                if (connection_status() !== CONNECTION_NORMAL) {
                    echo "Connection aborted";
                }
                fclose($handle);
            } else {
                ob_clean();
                flush();
                readfile($filePath);
            }
        } else {
            echo 'File does not exist!';
        }
    } else {
        echo 'There is no file to download!';
    }
    exit;
}
function curl_get($url)
{

    $head[] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0";
    // $head[] = "cept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    // $head[] = "Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3";
    // $head[] = "Accept-Encoding: gzip, deflate";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_ENCODING, ''); //允许执行gzip
    curl_setopt($ch, CURLOPT_NOSIGNAL, true); //支持毫秒级别超时设置
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
    if (!empty($head) && is_array($head)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
    }
    $data = curl_exec($ch);
    // var_dump($ch);exit;
    $info = curl_getinfo($ch);
    curl_close($ch);
    return $data;
}

function curl_post($url, $post_data)
{
    $ch = curl_init();
    $header = array("Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //设置HTTP头
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置是否返回信息
    $info = curl_exec($ch); //接收返回信息
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    curl_close($ch); //关闭curl链接
    //$result = json_decode($info, true);
    $result = $info;
    return $result;
}

// function curl_post($url,$post_data,$sid=''){
//     $ch          = curl_init();
//     $header      = array("Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8");
//     curl_setopt($ch, CURLOPT_POST, true);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//     curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //设置HTTP头
//     curl_setopt($ch, CURLOPT_URL, $url);
//     curl_setopt($ch, CURLOPT_COOKIE,'sid='.$sid);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置是否返回信息
//     $info = curl_exec($ch); //接收返回信息
//     if (curl_errno($ch)) {
//         print curl_error($ch);
//     }
// //    var_dump(curl_getinfo($ch));exit;
//     curl_close($ch); //关闭curl链接
//     // return $info;
//    $result = json_decode($info, true);
//     return $result;
// }
/**
 *
 */
function videoRename($id)
{
    $cid = $id;
    $root_path = $_SERVER['DOCUMENT_ROOT'];
    $dir = opendir($root_path . '/test/' . $cid);
    $list = array();
    while (($file = readdir($dir)) !== false) {
        if ($file != "." && $file != "..") {
            $arr = explode('.', $file);
            if ($arr['1'] == 'mp4') {
                array_push($list, $file);
            }
        }
    }
    closedir($dir);
    asort($list);
    foreach ($list as $key => $value) {
        $old_name = $root_path . '/test/' . $cid . '/' . $value;
        $num = $key + 1;
        $new_name = $root_path . '/test/' . $cid . '/' . $cid . '_00_000' . $num . '.mp4';
        if ($old_name != $new_name) {
            if (!rename($old_name, $new_name)) {
                return false;
            }
        }
    }
    return true;
}

/**
 *
 */
function toVoice($id)
{
    $cid = $id;
    $root_path = '/home/wwwroot/default';
    $dir = opendir($root_path . '/test/' . $cid);
    while (($file = readdir($dir)) !== false) {
        if ($file != "." && $file != "..") {
            $arr = explode('.', $file);
            if ($arr['1'] == 'mp4') {
                $mp3_name = $root_path . '/test/' . $cid . '/' . $arr['0'] . '.mp3';
                if (!file_exists($mp3_name)) {
                    $shell = $shell = 'ffmpeg -i ' . $root_path . '/test/' . $cid . '/' . $file . ' -vn  -acodec libmp3lame -ac 2 -qscale:a 4 -ar 48000 ' . $root_path . '/test/' . $cid . '/' . $arr['0'] . '.mp3';
                    system($shell);
                    //执行mp4转mp3的脚本语言
                }
            }
        }
    }
    closedir($dir);
    return true;
}

/**
 * 删除指定的文件夹
 */
function deldir($dir)
{
    //先删除目录下的文件：
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹：
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

function mimeTypes()
{
    /* Just add any required MIME type if you are going to download something not listed here.*/

    $mime_types = array(
        "323" => "text/h323",
        "acx" => "application/internet-property-stream",
        "ai" => "application/postscript",
        "aif" => "audio/x-aiff",
        "aifc" => "audio/x-aiff",
        "aiff" => "audio/x-aiff",
        "asf" => "video/x-ms-asf",
        "asr" => "video/x-ms-asf",
        "asx" => "video/x-ms-asf",
        "au" => "audio/basic",
        "avi" => "video/x-msvideo",
        "axs" => "application/olescript",
        "bas" => "text/plain",
        "bcpio" => "application/x-bcpio",
        "bin" => "application/octet-stream",
        "bmp" => "image/bmp",
        "c" => "text/plain",
        "cat" => "application/vnd.ms-pkiseccat",
        "cdf" => "application/x-cdf",
        "cer" => "application/x-x509-ca-cert",
        "class" => "application/octet-stream",
        "clp" => "application/x-msclip",
        "cmx" => "image/x-cmx",
        "cod" => "image/cis-cod",
        "cpio" => "application/x-cpio",
        "crd" => "application/x-mscardfile",
        "crl" => "application/pkix-crl",
        "crt" => "application/x-x509-ca-cert",
        "csh" => "application/x-csh",
        "css" => "text/css",
        "dcr" => "application/x-director",
        "der" => "application/x-x509-ca-cert",
        "dir" => "application/x-director",
        "dll" => "application/x-msdownload",
        "dms" => "application/octet-stream",
        "doc" => "application/msword",
        "dot" => "application/msword",
        "dvi" => "application/x-dvi",
        "dxr" => "application/x-director",
        "eps" => "application/postscript",
        "etx" => "text/x-setext",
        "evy" => "application/envoy",
        "exe" => "application/octet-stream",
        "fif" => "application/fractals",
        "flr" => "x-world/x-vrml",
        "gif" => "image/gif",
        "gtar" => "application/x-gtar",
        "gz" => "application/x-gzip",
        "h" => "text/plain",
        "hdf" => "application/x-hdf",
        "hlp" => "application/winhlp",
        "hqx" => "application/mac-binhex40",
        "hta" => "application/hta",
        "htc" => "text/x-component",
        "htm" => "text/html",
        "html" => "text/html",
        "htt" => "text/webviewhtml",
        "ico" => "image/x-icon",
        "ief" => "image/ief",
        "iii" => "application/x-iphone",
        "ins" => "application/x-internet-signup",
        "isp" => "application/x-internet-signup",
        "jfif" => "image/pipeg",
        "jpe" => "image/jpeg",
        "jpeg" => "image/jpeg",
        "jpg" => "image/jpeg",
        "js" => "application/x-javascript",
        "latex" => "application/x-latex",
        "lha" => "application/octet-stream",
        "lsf" => "video/x-la-asf",
        "lsx" => "video/x-la-asf",
        "lzh" => "application/octet-stream",
        "m13" => "application/x-msmediaview",
        "m14" => "application/x-msmediaview",
        "m3u" => "audio/x-mpegurl",
        "man" => "application/x-troff-man",
        "mdb" => "application/x-msaccess",
        "me" => "application/x-troff-me",
        "mht" => "message/rfc822",
        "mhtml" => "message/rfc822",
        "mid" => "audio/mid",
        "mny" => "application/x-msmoney",
        "mov" => "video/quicktime",
        "movie" => "video/x-sgi-movie",
        "mp2" => "video/mpeg",
        "mp3" => "audio/mpeg",
        "mpa" => "video/mpeg",
        "mpe" => "video/mpeg",
        "mpeg" => "video/mpeg",
        "mpg" => "video/mpeg",
        "mpp" => "application/vnd.ms-project",
        "mpv2" => "video/mpeg",
        "ms" => "application/x-troff-ms",
        "mvb" => "application/x-msmediaview",
        "nws" => "message/rfc822",
        "oda" => "application/oda",
        "p10" => "application/pkcs10",
        "p12" => "application/x-pkcs12",
        "p7b" => "application/x-pkcs7-certificates",
        "p7c" => "application/x-pkcs7-mime",
        "p7m" => "application/x-pkcs7-mime",
        "p7r" => "application/x-pkcs7-certreqresp",
        "p7s" => "application/x-pkcs7-signature",
        "pbm" => "image/x-portable-bitmap",
        "pdf" => "application/pdf",
        "pfx" => "application/x-pkcs12",
        "pgm" => "image/x-portable-graymap",
        "pko" => "application/ynd.ms-pkipko",
        "pma" => "application/x-perfmon",
        "pmc" => "application/x-perfmon",
        "pml" => "application/x-perfmon",
        "pmr" => "application/x-perfmon",
        "pmw" => "application/x-perfmon",
        "pnm" => "image/x-portable-anymap",
        "pot" => "application/vnd.ms-powerpoint",
        "ppm" => "image/x-portable-pixmap",
        "pps" => "application/vnd.ms-powerpoint",
        "ppt" => "application/vnd.ms-powerpoint",
        "prf" => "application/pics-rules",
        "ps" => "application/postscript",
        "pub" => "application/x-mspublisher",
        "qt" => "video/quicktime",
        "ra" => "audio/x-pn-realaudio",
        "ram" => "audio/x-pn-realaudio",
        "ras" => "image/x-cmu-raster",
        "rgb" => "image/x-rgb",
        "rmi" => "audio/mid",
        "roff" => "application/x-troff",
        "rtf" => "application/rtf",
        "rtx" => "text/richtext",
        "scd" => "application/x-msschedule",
        "sct" => "text/scriptlet",
        "setpay" => "application/set-payment-initiation",
        "setreg" => "application/set-registration-initiation",
        "sh" => "application/x-sh",
        "shar" => "application/x-shar",
        "sit" => "application/x-stuffit",
        "snd" => "audio/basic",
        "spc" => "application/x-pkcs7-certificates",
        "spl" => "application/futuresplash",
        "src" => "application/x-wais-source",
        "sst" => "application/vnd.ms-pkicertstore",
        "stl" => "application/vnd.ms-pkistl",
        "stm" => "text/html",
        "svg" => "image/svg+xml",
        "sv4cpio" => "application/x-sv4cpio",
        "sv4crc" => "application/x-sv4crc",
        "t" => "application/x-troff",
        "tar" => "application/x-tar",
        "tcl" => "application/x-tcl",
        "tex" => "application/x-tex",
        "texi" => "application/x-texinfo",
        "texinfo" => "application/x-texinfo",
        "tgz" => "application/x-compressed",
        "tif" => "image/tiff",
        "tiff" => "image/tiff",
        "tr" => "application/x-troff",
        "trm" => "application/x-msterminal",
        "tsv" => "text/tab-separated-values",
        "txt" => "text/plain",
        "uls" => "text/iuls",
        "ustar" => "application/x-ustar",
        "vcf" => "text/x-vcard",
        "vrml" => "x-world/x-vrml",
        "wav" => "audio/x-wav",
        "wcm" => "application/vnd.ms-works",
        "wdb" => "application/vnd.ms-works",
        "wks" => "application/vnd.ms-works",
        "wmf" => "application/x-msmetafile",
        "wps" => "application/vnd.ms-works",
        "wri" => "application/x-mswrite",
        "wrl" => "x-world/x-vrml",
        "wrz" => "x-world/x-vrml",
        "xaf" => "x-world/x-vrml",
        "xbm" => "image/x-xbitmap",
        "xla" => "application/vnd.ms-excel",
        "xlc" => "application/vnd.ms-excel",
        "xlm" => "application/vnd.ms-excel",
        "xls" => "application/vnd.ms-excel",
        "xlt" => "application/vnd.ms-excel",
        "xlw" => "application/vnd.ms-excel",
        "xof" => "x-world/x-vrml",
        "xpm" => "image/x-xpixmap",
        "xwd" => "image/x-xwindowdump",
        "z" => "application/x-compress",
        "rar" => "application/x-rar-compressed",
        "zip" => "application/zip"
    );
    return $mime_types;
}

function read_dir($dir, $type)
{
    $files = array();
    $dir_list = scandir($dir);
    foreach ($dir_list as $file) {
        if ($file != '..' && $file != '.') {
            if (is_dir($dir . '/' . $file)) {
                $files[] = read_dir($dir . '/' . $file, $type);
            } else {
                if (pathinfo($file, PATHINFO_EXTENSION) == $type) {
                    $files[] = $file;
                }
                // $files[]=$file;
            }
        }
    }
    return $files;
}

/**
 * 储存单位转换
 * 参数
 * byte 字节数
 */
function trans_byte($byte)
{
    $KB = 1024;
    $MB = 1024 * $KB;
    $GB = 1024 * $MB;
    $TB = 1024 * $GB;
    if ($byte < $KB) {
        return $byte . "B";
    } elseif ($byte < $MB) {
        return round($byte / $KB, 2) . "KB";
    } elseif ($byte < $GB) {
        return round($byte / $MB, 2) . "MB";
    } elseif ($byte < $TB) {
        return round($byte / $GB, 2) . "GB";
    } else {
        return round($byte / $TB, 2) . "TB";
    }
}

//获取用户真实IP
function getIp() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else
        if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else
            if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                $ip = getenv("REMOTE_ADDR");
            else
                if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                    $ip = $_SERVER['REMOTE_ADDR'];
                else
                    $ip = "unknown";
    return ($ip);
}


// 获取url
function getUrl() {
    return 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
